package com.tg.app.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.alibaba.fastjson.JSON;
import com.appbase.custom.constant.CommonConstants;
import com.tg.app.R;
import com.tg.app.activity.device.CameraViewActivity;
import com.tange.module.device.feature.DeviceFeature;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.listener.OnCameraZoomListener;
import com.tg.app.listener.OnZoomViewListener;
import com.tg.app.widget.BottomSheetListDialog;
import com.tg.app.widget.ForeSightView;
import com.tg.app.widget.ZoomPanTextureView;
import com.tg.app.widget.ZoomView;
import com.tange.base.toolkit.DimenUtil;
import com.tg.appcommon.android.ImageUtils;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.data.bean.DeviceItem;
import com.tg.data.http.entity.AVFrames;

public class CameraPlayerPiPVerticalView extends CameraPlayerPiPView {
    private static final String TAG = "CameraPlayerPiPVerticalView";
    private RelativeLayout mMainLayout, mMiniLayout;
    private ImageView mMainImageView, mMiniImageView;
    private ConstraintLayout viewLayout;
    protected DisplayMetrics displayMetrics;
    private int pad;
    private int saveLivePlayer = -1;
    private OnSwitchPlayerListener onSwitchPlayerListener;
    private boolean live2Playback = false;
    private ZoomView mZoomView1, mZoomView2;
    private TextView mZoomTextView1, mZoomTextView2;
    private boolean mShowZoom1 = false, mShowZoom2 = false;
    protected ForeSightView foreSightViewSub;
    protected boolean isForeSightSubEnable;

    public void setForeSightSubEnable(boolean foreSightEnable) {
        isForeSightSubEnable = foreSightEnable;
        updateForeSight();
    }

    @Override
    protected void updateForeSight() {
        super.updateForeSight();
         if (isForeSightSubEnable &&foreSightViewSub!=null){
            foreSightViewSub.setVisibility(GONE);
            textureViewMini.setZoomRange(1,1);
            foreSightViewSub.setListener((x, y) -> {
                if (foreSightListener!=null){
                    foreSightListener.onForeSightChanged(1,x,y);
                }
            });
        }
    }

    public void setZoomFactor(float zoomFactor, int channel) {
        TGLog.d(ZoomView.TAG, "CameraPlayerPiPVerticalView = " + zoomFactor + ", channel = " + channel);
        if (channel == 0){
            mZoomView1.setZoomFactor(zoomFactor);
        }else{
            mZoomView2.setZoomFactor(zoomFactor);
        }
    }

    public void hideZoomTextView(int index){
        if (index == 0){
            mZoomTextView1.setVisibility(GONE);
        }else{
            mZoomTextView2.setVisibility(GONE);
        }
    }

    public void setZoomTextView(String text, int index) {

        if (index == 0){
            mZoomTextView1.setVisibility(VISIBLE);
            mZoomTextView1.setText(text);
        }else{
            mZoomTextView2.setVisibility(VISIBLE);
            mZoomTextView2.setText(text);
        }
    }

    public void bringToFrontZoom(int channel){
        if (channel == 0){
            mZoomView1.bringToFront();
            mZoomTextView1.bringToFront();
        }else{
            mZoomView2.bringToFront();
            mZoomTextView2.bringToFront();
        }
    }
    public void parseZoomParam(DeviceFeature.ZoomFeature zoomFeature){
        if (zoomFeature != null){
            if (zoomFeature.index == 0){
                mZoomView1.parseZoomParam(zoomFeature);
            }else{
                mZoomView2.parseZoomParam(zoomFeature);
            }
        }
    }


    public void setOnCameraZoomListener(OnCameraZoomListener onCameraZoomListener, int channel) {
        if (channel == 0){
            mZoomView1.setOnCameraZoomListener(onCameraZoomListener);
        }else{
            mZoomView2.setOnCameraZoomListener(onCameraZoomListener);
        }
    }


    public void initZoom(DeviceFeature.ZoomFeature zoomFeature, int index) {
        TGLog.d(ZoomView.TAG, "mShowZoom1 = " + mShowZoom1 + ", mShowZoom2 = " + mShowZoom2 + ", index = " + index + ", zoomFeature = " + zoomFeature);
        if (zoomFeature != null){
            if (zoomFeature.index == 0){
                mShowZoom1 = true;
                mZoomView1.initZoom(zoomFeature);
            }else{
                mShowZoom2 = true;
                mZoomView2.initZoom(zoomFeature);
            }
        }else if (index == 0){
            mShowZoom1 = false;
            mZoomView1.setVisibility(View.GONE);
        }else {
            mShowZoom2 = false;
            mZoomView2.setVisibility(View.GONE);
        }
    }

    @Override
    public void recordStart() {
        super.recordStart();
        setSeekBarEnabled(false);
    }

    private void setSeekBarEnabled(boolean b) {
        if (isMainPlayer()) {
            if (mShowZoom2) {
                mZoomView2.setSeekBarEnabled(b);
            }
        } else {
            if (mShowZoom1) {
                mZoomView1.setSeekBarEnabled(b);
            }
        }
    }

    @Override
    public void recordEnd() {
        super.recordEnd();
        setSeekBarEnabled(true);

    }

    public void setOnSwitchPlayerListener(OnSwitchPlayerListener onSwitchPlayerListener) {
        this.onSwitchPlayerListener = onSwitchPlayerListener;
    }

    public CameraPlayerPiPVerticalView(@NonNull Context context) {
        super(context);
    }

    public CameraPlayerPiPVerticalView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CameraPlayerPiPVerticalView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context) {
        initRes();
        super.init(context);
        pad = DimenUtil.dp2px(context, 2);
    }

    private void initRes() {
        displayMetrics = getResources().getDisplayMetrics();

    }

    @Override
    public void setOpenOverlap(boolean openOverlap) {
        super.setOpenOverlap(openOverlap);
    }

    @Override
    protected void initView(View view) {
        mMainLayout = view.findViewById(R.id.player_view_pip_vertical_main);
        mMiniLayout = view.findViewById(R.id.player_view_pip_vertical_mini);
        mMainImageView = view.findViewById(R.id.camera_player_pip_view_vertical_bg_main);
        mMiniImageView = view.findViewById(R.id.camera_player_pip_view_vertical_bg_mini);
        viewLayout = view.findViewById(R.id.camera_player_view_layout);
        mZoomView1 = view.findViewById(R.id.camera_player1_zoomview);
        mZoomView2 = view.findViewById(R.id.camera_player2_zoomview);
        mZoomTextView1 = view.findViewById(R.id.tv_zoom1);
        mZoomTextView2 = view.findViewById(R.id.tv_zoom2);
        foreSightView = view.findViewById(R.id.camera_player1_fore_sight_view);
        foreSightViewSub = view.findViewById(R.id.camera_player2_fore_sight_view);
    }


    private boolean canClick() {
        Object object = TGApplicationBase.getInstance().getGlobalObject(BottomSheetListDialog.ACTION_RESOLUTION);
        if (object instanceof Boolean) {
            return !(isLandscape() && (Boolean) object);
        }
        return true;
    }

    public void setZoomView(int visible) {
        boolean isSupportMultiChannels = DeviceFeatureHelper.supportMultiChannels(mDeviceFeature);
        if (!isSupportMultiChannels){
            return;
        }
        int ld = getLayoutDirection();
        if (visible == View.VISIBLE) {
            if (mShowZoom1){
                mZoomView1.setVisibility(VISIBLE);
                mZoomView1.animate().translationX(0).setDuration(240).setListener(null).start();
            }
            if (mShowZoom2){
                mZoomView2.setVisibility(VISIBLE);
                mZoomView2.animate().translationX(0).setDuration(240).setListener(null).start();
            }

            bringToFrontZoom(0);
            bringToFrontZoom(1);
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                if (isMainPlayer()){
                    HideZoomView(mZoomView2, mZoomTextView2);
                }else{
                    HideZoomView(mZoomView1, mZoomTextView1);
                }
            }
        } else {
            if (mZoomView1.getVisibility() == VISIBLE){
                int zoomW = DimenUtil.dp2px(mContext, 80);
                if (ld == View.LAYOUT_DIRECTION_RTL) {
                    zoomW = -zoomW;
                }

                mZoomView1.animate().translationX(zoomW).setDuration(240).setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        HideZoomView(mZoomView1, mZoomTextView1);
                    }
                }).start();

            }
            if (mZoomView2.getVisibility() == VISIBLE){
                int zoomW = DimenUtil.dp2px(mContext, 80);
                if (ld == View.LAYOUT_DIRECTION_RTL) {
                    zoomW = -zoomW;
                }

                mZoomView2.animate().translationX(zoomW).setDuration(240).setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        HideZoomView(mZoomView2, mZoomTextView2);
                    }
                }).start();


            }
        }
    }

    private void HideZoomView(LinearLayout zoomView, TextView zoomTextView) {
        TGLog.d(ZoomView.TAG, "zoomView" + zoomView + ", zoomTextView = " + zoomTextView);
        zoomView.setVisibility(View.GONE);
        zoomTextView.setVisibility(GONE);
    }

    @Override
    public void setListener() {
        super.setListener();
        textureView.setDrag(false);
        textureViewMini.setDrag(false);
        textureView.setZoomRange(1.0f, 1.0f);
        textureViewMini.setZoomRange(1.0f, 1.0f);
        textureView.setOnZoomViewListener(new OnZoomViewListener() {
            @Override
            public void onSingleClick(boolean show) {
                TGLog.d(ZoomView.TAG, "textureView showZoom1 = " + mShowZoom1 + ", showZoom2 = " + mShowZoom2);
                if (isVerticalModePortrait()) {
                    if (!isMainPlayer()) {
                        if (isRecording) {
                            MsgCenterToast.show(getContext(), R.string.camera_player_screencap);
                            return;
                        }
                        currentPlayer = PLAYER_ID_MAIN;
                        updateSelectViewBg(true);
                        show = true;
                    }
                    if (onZoomViewListener == null) return;
                    onZoomViewListener.onSingleClick(show);
                    return;
                }
                if (isMainPlayer()) {
                    if (onZoomViewListener == null) return;
                    onZoomViewListener.onSingleClick(show);
                } else if (canClick()) {
                    switchPlayer(PLAYER_ID_MAIN);
                }
            }

            @Override
            public void onScale(float scale) {
                if (onZoomViewListener != null) {
                    onZoomViewListener.onScale(scale);
                }
            }
        });
        textureViewMini.setOnZoomViewListener(new OnZoomViewListener() {
            @Override
            public void onSingleClick(boolean show) {
                TGLog.d(ZoomView.TAG, "textureViewMini showZoom1 = " + mShowZoom1 + ", showZoom2 = " + mShowZoom2);
                if (isVerticalModePortrait()) {
                    if (playbackPipNone()) return;
                    if (isMainPlayer()) {
                        if (isRecording) {
                            MsgCenterToast.show(getContext(), R.string.camera_player_screencap);
                            return;
                        }
                        currentPlayer = PLAYER_ID_MINI;
                        updateSelectViewBg(true);
                        show = true;
                    }
                    if (onZoomViewListener == null) return;
                    onZoomViewListener.onSingleClick(show);
                    return;
                }
                if (!isMainPlayer()) {
                    if (onZoomViewListener == null) return;
                    onZoomViewListener.onSingleClick(show);
                } else if (canClick()) {
                    switchPlayer(PLAYER_ID_MINI);
                }


            }

            @Override
            public void onScale(float scale) {
                if (onZoomViewListener != null) {
                    onZoomViewListener.onScale(scale);
                }
            }
        });
    }

    public void switchPlayer() {
        TGLog.d(TAG,"switchPlayer currentPlayer " + currentPlayer);
        if (isMainPlayer()) {
            switchPlayer(PLAYER_ID_MINI);
        } else {
            switchPlayer(PLAYER_ID_MAIN);
        }
    }

    public void switchPlayer(int viewId) {
        if (currentPlayer == viewId) return;
        if (isRecording) {
            MsgCenterToast.show(getContext(), R.string.camera_player_screencap);
            return;
        }

        isUpdateViewSizeEnable = true;
        TGLog.d(TAG,"switchPlayer currentPlayer2 : " + currentPlayer + " viewId: " + viewId);
        currentPlayer = viewId;
        if (onCameraPlayerListener != null) {
            onCameraPlayerListener.onChanged(currentPlayer);
        }
        if (isOverlapLive() && !isLandscape()) {
            setLivePortraitOverlapLayout();
        } else {
            setPlaybackLayout(isLandscape(), true);
        }
        updateSwitch(true);
        updateListener();
        switchZoom(viewId);
    }

    public void switchZoom(int viewId){
        if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)){
            if (viewId == PLAYER_ID_MAIN){
                if (mShowZoom1){
                    mZoomView1.setVisibility(VISIBLE);
                    textureViewMini.setVisibility(VISIBLE);
                    textureViewMini.bringToFront();
                    if (isForeSightSubEnable){
                        foreSightViewSub.bringToFront();
                    }
                }
                if (mShowZoom2){
                    HideZoomView(mZoomView2, mZoomTextView2);
                }
            }else {
                if (mShowZoom2){
                    mZoomView2.setVisibility(VISIBLE);
                    textureView.setVisibility(VISIBLE);
                    textureView.bringToFront();
                    if (isForeSightEnable){
                        textureView.bringToFront();
                    }
                }
                if (mShowZoom1){
                    HideZoomView(mZoomView1, mZoomTextView1);
                }
            }

            bringToFrontZoom(1 - viewId);
            bringToFrontZoom(viewId);
        }
    }


    private void updateSwitch(boolean cmd) {
        if (onSwitchPlayerListener != null) {
            onSwitchPlayerListener.onSwitchPlayer(currentPlayer, cmd);
        }
    }

    void updateSelectViewBg(boolean cmd) {
        updateSwitch(cmd);
        updateListener();
        selectedLayout();
    }
    void selectedLayout(){
        if (isSdcardPipNone()||isCloudPipNone())return;
        if (isMainPlayer()) {
            mMainLayout.setPadding(pad, pad, pad, pad);
            mMainLayout.setBackgroundResource(R.drawable.player_view_pip_vertical_selected);
            mMiniLayout.setBackgroundColor(Color.TRANSPARENT);
            mMainLayout.bringToFront();
            mMiniLayout.setPadding(0, 0, 0, 0);
        } else {
            mMainLayout.setBackgroundColor(Color.TRANSPARENT);
            mMiniLayout.setBackgroundResource(R.drawable.player_view_pip_vertical_selected);
            mMiniLayout.setPadding(pad, pad, pad, pad);
            mMiniLayout.bringToFront();

            mMainLayout.setPadding(0, 0, 0, 0);
        }
    }

    @Override
    protected int getLayoutID() {
        return R.layout.layout_camera_player_pip_vertical;
    }

    @Override
    protected int getPiPType() {
        return CameraPlayerPiPType.Vertical;
    }

    @Override
    public void receiveVideoData(@NonNull AVFrames avFrame) {
        int codec = avFrame.getMediaCodec();
        if (codec != AVIOCTRLDEFs.MEDIA_CODEC_UNKNOWN) {
            fixMediaSyncOnce(codec);
            nCodecId = codec;
            if (mustHide(true)) {
                TGThreadPool.executeOnUiThread(() -> textureView.setVisibility(GONE));
                return;
            }
            mediaSync.addVideo(avFrame);

            if (textureView.getVisibility() != VISIBLE) {
                TGThreadPool.executeOnUiThread(() -> {
                    textureView.setVisibility(VISIBLE);
                    loadingHide();
                });

            }
        }
    }


    private boolean mustHide(boolean isMainPlayer) {
        if (isVerticalModePortrait()) return false;
        if (isMainPlayer() == isMainPlayer) {
            return false;
        } else {
            return !getPipShowStatus();
        }
    }

    boolean isVerticalModePortrait() {
        return isVertical() && !isLandscape();
    }

    @Override
    public void receiveVideoMiniData(@NonNull AVFrames avFrame) {
        int codec = avFrame.getMediaCodec();
        if (codec != AVIOCTRLDEFs.MEDIA_CODEC_UNKNOWN) {
            fixMediaSyncOnce(codec);
            nMiniCodecId = codec;
            if (avFrame.isPlayback()){
                if (isSdcardPipNone()) {
                    isSdCardPipVideo = true;
                    if (mDevice!=null){
                        PreferenceUtil.setBoolean(mContext,localSdCardPip(),isSdCardPipVideo);
                    }
                    setPlaybackPip();
                } else if (isCloudPipNone()) {
                    isCloudPipVideo = true;
                    if (mDevice!=null){
                        PreferenceUtil.setBoolean(mContext,localCloudPip(),isCloudPipVideo);
                    }
                    setPlaybackPip();
                }
            }

            if (mustHide(false)) {
                TGThreadPool.executeOnUiThread(() -> textureViewMini.setVisibility(GONE));
                return;
            }
            mediaSyncMini.addVideo(avFrame);
            if (!isTextureViewMiniShow()) {
                TGLog.d(TAG,"textureViewMini.getVisibility() " + textureViewMini.getVisibility());
                TGThreadPool.executeOnUiThread(() -> {
                    TGLog.d(TAG,"textureViewMini.setVisibility 1: "+JSON.toJSONString(avFrame.isPlayback()));
                    textureViewMini.setVisibility(VISIBLE);
                    loadingHide();
                });

            }
        }
    }

    private void setPlaybackPip() {
        if (mFloatView != null && mFloatView.getVisibility() == VISIBLE) {
            setPipBtnVisibilityAnimation(VISIBLE);
        }
        if (isVertical() && !isLivePlayType()) {
            mMiniLayout.setVisibility(VISIBLE);
            selectedLayout();
        }
    }

    @Override
    public void setDevice(@NonNull DeviceItem mDevice) {
        super.setDevice(mDevice);
        ImageUtils.loadImage(mContext, mMainImageView, mDevice.image_path, false);
        ImageUtils.loadImage(mContext, mMiniImageView, mDevice.image_path, false);
        isCloudPipVideo = PreferenceUtil.getBoolean(mContext,localCloudPip());
        isSdCardPipVideo = PreferenceUtil.getBoolean(mContext,localSdCardPip());

    }
    private String localCloudPip(){
        return String.format("%s_cloud_pip",mDevice.uuid);
    }
    private String localSdCardPip(){
        return String.format("%s_sdcard_pip",mDevice.uuid);
    }

    @Override
    protected void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        udpateViewByOrientation(newConfig.orientation);
    }


    protected void setLayoutMargin() {
        FrameLayout.LayoutParams params = (LayoutParams) viewLayout.getLayoutParams();
        params.topMargin = 0;
        params.bottomMargin = 0;
        viewLayout.setLayoutParams(params);
    }

    private int getLandscapeWidth() {
        int width = (int) (displayMetrics.widthPixels * getAspectRatio());
        if (width >= displayMetrics.heightPixels) {
            width = displayMetrics.heightPixels;
        }
        return width;
    }

    private int getPlayerHeight() {
        return (int) getResources().getDimension(R.dimen.player_height);
    }

    private void setLayoutFull() {
        mMiniLayout.setBackgroundColor(Color.TRANSPARENT);
        mMainLayout.setBackgroundColor(Color.TRANSPARENT);
        RelativeLayout.LayoutParams videoParams = createRelativeLayoutParams();
        if (isLandscape()) {
            videoParams.width = getLandscapeWidth();
            TGLog.d(TAG,"displayMetrics 2 width :" + displayMetrics.widthPixels + " dis: " + getLandscapeWidth());
        } else {
            videoParams.width = displayMetrics.widthPixels;
            videoParams.height = getPlayerHeight();
        }
        TGLog.d(TAG,"displayMetrics width :" + displayMetrics.widthPixels + " dis: " + displayMetrics.heightPixels + " video height: " + videoParams.height);

        ConstraintLayout.LayoutParams params = getFullConstraintLayoutParams();
        mMainLayout.setLayoutParams(params);
        mMiniLayout.setLayoutParams(params);
        mMiniLayout.setPadding(0, 0, 0, 0);
        mMainLayout.setPadding(0, 0, 0, 0);
        setLayout(videoParams);
    }

    private void setLayout(RelativeLayout.LayoutParams videoParams) {
        if (isMainPlayer()) {

            mMainImageView.setLayoutParams(videoParams);
            mMainImageView.setVisibility(VISIBLE);
            textureView.setLayoutParams(videoParams);
            TGLog.d(TAG,"textureView w:" + videoParams.width + " H: " + videoParams.height);
            if (!isMiniVideoOpen) {
                textureViewMini.setVisibility(GONE);
            }

        } else {
            mMiniImageView.setLayoutParams(videoParams);
            mMiniImageView.setVisibility(VISIBLE);
            TGLog.d(TAG,"textureViewMini w:" + videoParams.width + " H: " + videoParams.height);
            textureViewMini.setLayoutParams(videoParams);
            if (!isMiniVideoOpen) {
                textureView.setVisibility(GONE);
            }
        }
    }

    private ConstraintLayout.LayoutParams getFullConstraintLayoutParams() {
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        params.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
        params.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        params.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
        params.width = 0;
        params.height = 0;
        return params;
    }

    private void setTextureViewTranslationX(boolean exchange) {
        float x = 0;
        float y = 0;
        float dx = 0;
        float dy = 0;
        if (exchange) {
            if (isMainPlayer()) {
                dx = textureView.getTranslationX();
                dy = textureView.getTranslationY();

            } else {
                x = textureViewMini.getTranslationX();
                y = textureViewMini.getTranslationY();
            }
        }
        textureView.setTranslationX(x);
        textureView.setTranslationY(y);
        textureViewMini.setTranslationX(dx);
        textureViewMini.setTranslationY(dy);

    }

    private void setMiniToBottomRight(int miniWidth, int miniHeight, int right, int bottom) {

        ConstraintLayout.LayoutParams layoutParams = getFullConstraintLayoutParams();
        RelativeLayout.LayoutParams videoParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        videoParams.width = miniWidth;
        videoParams.height = miniHeight;
        videoParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        videoParams.rightMargin = right;
        videoParams.bottomMargin = bottom;
        if (isMainPlayer()) {
            mMiniImageView.setVisibility(GONE);
            mMiniLayout.setLayoutParams(layoutParams);
            textureViewMini.setLayoutParams(videoParams);
            mMiniLayout.bringToFront();
            TGLog.d(TAG,"textureViewMini1  w:" + videoParams.width + " H: " + videoParams.height);
        } else {
            mMainImageView.setVisibility(GONE);
            mMainLayout.setLayoutParams(layoutParams);
            textureView.setLayoutParams(videoParams);
            mMainLayout.bringToFront();
            TGLog.d(TAG,"textureView1 w:" + videoParams.width + " H: " + videoParams.height);
        }
    }

    protected float getHalfHeight() {
        return ((getHeight()) * 1.0f / 2);
    }

    private int getVideoWidth() {
        if (isOverlapLive() || isVerticalPlayback()) {
            return displayMetrics.widthPixels;
        }
        int width = (int) (getHalfHeight() * getAspectRatio());
        int w = getWidth();
        return Math.min(width, w);
    }

    private void setLivePortraitOverlapLayout() {

        TGLog.d(TAG,"setLivePortraitOverlapLayout");
        int miniWidth = (int) getResources().getDimension(R.dimen.camera_player_view_mini_width);
        int miniHeight = (int) getResources().getDimension(R.dimen.camera_player_view_mini_height);
        setLayoutMargin();
        setLayoutFull();
        setTextureViewTranslationX(false);
        int bottom = (int) ((getResources().getDimension(R.dimen.camera_view_player_height) - getPlayerHeight()) / 2);
        if (isOverlapLive()) {
            bottom -= DimenUtil.dp2px(mContext, 25);
        }
        setMiniToBottomRight(miniWidth, miniHeight, 0, bottom);
        setTextureViewDragAndZoom();
    }

    public ConstraintLayout.LayoutParams getMainLayoutParams(){
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.bottomToTop = R.id.player_view_pip_vertical_mini;
        layoutParams.bottomMargin = DimenUtil.dp2px(mContext, 1);
        return layoutParams;
    }

    public ConstraintLayout.LayoutParams getMiniLayoutParams(){
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.topToBottom = R.id.player_view_pip_vertical_main;
        layoutParams.topMargin = DimenUtil.dp2px(mContext, 1);
        return layoutParams;
    }

    public RelativeLayout.LayoutParams getMiniTextureLayoutParams(int width, int height){
        RelativeLayout.LayoutParams miniParams = new RelativeLayout.LayoutParams(width, height);
        miniParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        return miniParams;
    }

    public RelativeLayout.LayoutParams getMainTextureLayoutParams(int width, int height){
        RelativeLayout.LayoutParams mainParams = new RelativeLayout.LayoutParams(width, height);
        mainParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        return mainParams;
    }


    public void setLivePortraitLayout() {

        TGLog.d(TAG,"setLivePortraitLayout");
        setLayoutMargin();
        int layoutHeight = (int) getHalfHeight();

        int playerHeight = getPlayerHeight();
        int width = getVideoWidth();
        int height = (int) (width / getAspectRatio());

        float less = 0.2f;
        boolean isLess = getHeight() < playerHeight * (1 + less);
        TGLog.d(TAG,"setLivePortraitLayout height: " + layoutHeight + " " + getAspectRatio());
        TGLog.d(TAG,"setLivePortraitLayout " + width);
        TGLog.d(TAG,"setLivePortraitLayout height: " + height);

        ConstraintLayout.LayoutParams layoutParams = getMainLayoutParams();
        if (isLess) {
            layoutParams.height = playerHeight * 9 / 10;
            width = displayMetrics.widthPixels;
        } else {
            layoutParams.height = layoutHeight;
            layoutParams.verticalWeight = 1;
        }

        layoutParams.width = displayMetrics.widthPixels;
        mMainLayout.setLayoutParams(layoutParams);


        ConstraintLayout.LayoutParams miniLayoutParams = getMiniLayoutParams();

        if (isLess) {
            miniLayoutParams.height = layoutHeight * 2 - layoutParams.height;

        } else {
            miniLayoutParams.height = layoutHeight;
            miniLayoutParams.verticalWeight = 1;
        }

        miniLayoutParams.width = displayMetrics.widthPixels;
        mMiniLayout.setLayoutParams(miniLayoutParams);

        RelativeLayout.LayoutParams mainParams = getMainTextureLayoutParams(width, height);

        if (isLess) {
            mainParams.height = layoutParams.height;
        } else {
            mainParams.height = height;
        }
        mMainImageView.setLayoutParams(mainParams);
        textureView.setLayoutParams(mainParams);
        if (isForeSightEnable&&foreSightView!=null){
            foreSightView.setLayoutParams(mainParams);
        }
        mMainImageView.setVisibility(VISIBLE);
        TGLog.d(TAG,"setLivePortraitLayout m width：" + width + " height :" + mainParams.height);

        RelativeLayout.LayoutParams miniParams = getMiniTextureLayoutParams(width, height);
        if (isLess) {
            TGLog.d(TAG,"===>>>>>  :");
            miniParams.height = miniLayoutParams.height;
        } else {
            miniParams.height = height;
            TGLog.d(TAG,"===>>>>> dddddddddddddddddddddd :");
        }
        mMiniImageView.setLayoutParams(miniParams);
        mMiniImageView.setVisibility(VISIBLE);
        textureViewMini.setLayoutParams(miniParams);
        if (isForeSightSubEnable&&foreSightViewSub!=null){
            foreSightViewSub.setLayoutParams(miniParams);
        }
        TGLog.d(TAG,"setLivePortraitLayout s width：" + width + " height :" + miniParams.height);

        int pad = DimenUtil.dp2px(mContext, 2);
        textureView.setTranslationX(0);
        textureView.setTranslationY(0);
        textureViewMini.setTranslationX(0);
        textureViewMini.setTranslationY(0);
        if (isForeSightEnable){
            textureView.setZoomRange(1, 1);
            if (isPlayLive){
                foreSightView.bringToFront();
            }

        }else{
            textureView.setZoomRange(1, 4);
        }
        textureView.setDrag(false);
        if (isForeSightSubEnable){
            textureViewMini.setZoomRange(1, 1);
            if (isPlayLive){
                foreSightViewSub.bringToFront();
            }
        }else {
            textureViewMini.setZoomRange(1, 4);
        }
        textureViewMini.setDrag(false);
        if (isMainPlayer()) {
            mMainLayout.setPadding(pad, pad, pad, pad);
        } else {
            mMiniLayout.setPadding(pad, pad, pad, pad);
        }

    }


    @Override
    public void setLiveViewShow(boolean playLive) {
        TGLog.i(TAG,"setLiveViewShow " + (playLive ? "true" : "false"));
        if (playLive==isPlayLive){
            live2Playback = false;
        }
        if (!isLandscape()) {
            super.setLiveViewShow(playLive);
            setPortraitLayout();
        }

    }

    private final OnGlobalLayoutListener onGlobalLayoutListener = new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            TGLog.d(TAG,"onGlobalLayout live2Playback");
            if (isVertical() && !isLandscape()) {
                setLivePortraitLayout();
            }
            if (!live2Playback) {
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        }
    };

    private void setPortraitLayout() {

        if (isVertical()) {
            getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
            if (isVertical()) {
                if (isPlayLive && saveLivePlayer != -1) {
                    currentPlayer = saveLivePlayer;
                }
                updateSelectViewBg(false);
            }
        } else {
            TGLog.d(TAG,"setLiveViewShow onGlobalLayout2 "+JSON.toJSONString(isOpenOverlap));
            if (isOpenOverlap) {
                if (onGlobalLayoutListener != null) {
                    getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
                }
                setPlaybackLayout(false, false);
            }
        }
    }

    private void setPlaybackLayout(boolean isLand, boolean exchange) {
        int miniWidth = (int) getResources().getDimension(R.dimen.camera_player_view_mini_width);
        int miniHeight = (int) getResources().getDimension(R.dimen.camera_player_view_mini_height);
        int right = 0;
        if (isLand) {
            miniWidth = (int) getResources().getDimension(R.dimen.camera_player_view_mini_width_land);
            miniHeight = (int) getResources().getDimension(R.dimen.camera_player_view_mini_height_land);
            right = (displayMetrics.heightPixels - getLandscapeWidth()) / 2;
        }
        setLayoutMargin();
        setLayoutFull();
        setTextureViewTranslationX(exchange);
        setMiniToBottomRight(miniWidth, miniHeight, right, 0);
        setTextureViewDragAndZoom();
        foreSightViewSub.setVisibility(GONE);
        foreSightView.setVisibility(GONE);
    }

    private void setTextureViewDragAndZoom() {

        if (isMainPlayer()) {
            textureView.setZoomRange(1, 4);
            textureView.setDrag(false);
            textureViewMini.setZoomRange(1, 1);
            textureViewMini.setDrag(true);
        } else {
            textureViewMini.setZoomRange(1, 4);
            textureViewMini.setDrag(false);
            textureView.setZoomRange(1, 1);
            textureView.setDrag(true);
        }
    }

    @Override
    public void setMediaType(int mediaType) {

        TGLog.i(TAG,"setMediaType " + mediaType);
        if (isLivePlayType()) {
            saveLivePlayer = currentPlayer;
            if (mediaType != this.mediaType) {
                live2Playback = true;
                TGLog.d(TAG,"live2Playback");
            }else {
                live2Playback = false;
            }
        }
        super.setMediaType(mediaType);
        if (isVertical()){
            if (!isLivePlayType()&&(isSdcardPipNone()||isCloudPipNone())){
                mMiniLayout.setVisibility(GONE);
                mMainLayout.setPadding(0,0,0,0);
                mMainLayout.setBackgroundColor(Color.TRANSPARENT);
            }else if (mMiniLayout.getVisibility() == GONE){
                mMiniLayout.setVisibility(VISIBLE);
                selectedLayout();
            }
        }

    }

    @Override
    protected void updateMediaType() {
        super.updateMediaType();
        if (!isLivePlayType()&&isForeSightSubEnable) {
            foreSightViewSub.setVisibility(GONE);
        }
    }

    public boolean playbackPipNone() {
        return isSdcardPipNone() || isCloudPipNone();
    }

    @Override
    protected int getVideoSizeHeight(int height) {
        return height;
    }

    @Override
    protected void updatePlayerViewSize(ZoomPanTextureView mTextureView, int width, int height) {
        TGLog.d(TAG,"isUpdateViewSizeEnable " + JSON.toJSONString(isUpdateViewSizeEnable));
        if (!isUpdateViewSizeEnable) return;
        if (textureView == mTextureView) {
            TGLog.d(TAG,"updatePlayerViewSize textureView: " + width + " height: " + height);
            textureView.setVideoSize(width, height);
        } else if (textureViewMini == mTextureView) {
            TGLog.d(TAG,"updatePlayerViewSize textureViewMini: " + width + " height: " + height);
            textureViewMini.setVideoSize(width, height);
        }
    }

    private boolean isTextureViewMiniShow() {
        return textureViewMini.getVisibility() == VISIBLE;
    }

    private RelativeLayout.LayoutParams createRelativeLayoutParams() {
        RelativeLayout.LayoutParams mainParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mainParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        return mainParams;
    }

    private boolean isSdcardPip() {
        return isSdcardPlayType() && isSdCardPipVideo;
    }
    private boolean isSdcardPipNone() {
        return isSdcardPlayType() && !isSdCardPipVideo;
    }
    private boolean isCloudPipNone() {
        return isCloudPlayType() && !isCloudPipVideo;
    }
    private boolean isCloudPip() {
        return isCloudPlayType() && isCloudPipVideo;
    }

    @Override
    public void switchPlayerHide() {
        super.switchPlayerHide();
        if (isSdcardPip()) {
            return;
        }
        if (isCloudPip()) {
            return;
        }
        setPipBtnVisibility(GONE);
        TGLog.d(TAG,"textureViewMini.setVisibility 00 >> "+currentPlayer);
        textureViewMini.setVisibility(GONE);
        textureView.setVisibility(GONE);
        int viewWidth = getWidth();
        int videoWidth = textureView.getWidth();
        TGLog.d(TAG,"viewWidth " + viewWidth + " videoWidth: " + videoWidth);
        if (isMainPlayer() || isVertical()) {
            return;
        }
        switchPlayer(PLAYER_ID_MAIN);
    }

    @Override
    public void updateView() {
        TGLog.d(TAG,"updateView live2Playback  " + (isPlayLive ? " true" : " false"));
        live2Playback = false;
        udpateViewByOrientation(getResources().getConfiguration().orientation);
    }


    @Override
    public void analogZoom(float scale, boolean animation,int duration, int index, String from) {

        if (isSurfaceTextureUpdated || StringUtils.equalsIgnoreCase(from, CameraViewActivity.ZOOM_INIT)){
            TGLog.d(TAG,"analogZoom ==> "+scale);
            if (index == 0){
                textureView.analogZoom(scale,duration,animation);
            }else{
                textureViewMini.analogZoom(scale,duration,animation);
            }

        }else {
            TGLog.d(TAG,"analogZoom analogZoomScale "+scale);
        }
    }

    @Override
    public void analogOverZoom(float startScale, float endScale,int duration, int index) {
        if (isSurfaceTextureUpdated){
            if (index == 0){
                textureView.analogZoom(startScale,2000,true);
            }else{
                textureViewMini.analogZoom(startScale,2000,true);
            }
        }
    }


    private void udpateViewByOrientation(int orientation) {
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) mSwitchVideoBtn.getLayoutParams();
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            layoutParams.leftMargin = DimenUtil.dp2px(mContext, 15);
            setPortraitLayout();
            if (isVertical()) {
                setPipBtnVisibilityAnimation(GONE);
                if (isForeSightSubEnable){
                    foreSightViewSub.setVisibility(VISIBLE);
                }
            }

        } else {
            setPipBtnVisibilityAnimation(VISIBLE);
            layoutParams.leftMargin = DimenUtil.dp2px(mContext, 30);
            setPlaybackLayout(true, false);
            foreSightViewSub.setVisibility(GONE);
        }
        mSwitchVideoBtn.setLayoutParams(layoutParams);
    }

    @Override
    public void playerHide() {
        TGLog.trace("playerHide");
        mediaSyncClear();
        ViewGroup.LayoutParams params = textureView.getLayoutParams();
        mMainLayout.removeView(textureView);
        textureView.setVisibility(GONE);
        mMainLayout.addView(textureView, params);
        ViewGroup.LayoutParams layoutParams = textureViewMini.getLayoutParams();
        textureViewMini.setVisibility(GONE);
        mMiniLayout.removeView(textureViewMini);
        mMiniLayout.addView(textureViewMini, layoutParams);
    }

    @Override
    protected void setBackgroundViewDrawable(Drawable resource) {
        mMainImageView.setBackground(resource);
        mMiniImageView.setBackground(resource);
    }

    @Override
    protected void setBackgroundClick() {
        super.setBackgroundClick();
        mMainImageView.setOnClickListener(onClickListener);
        mMiniImageView.setOnClickListener(onClickListener);
    }

    @Override
    public void setAnchorView(View view) {
        super.setAnchorView(view);
        mSwitchVideoBtn.setOnClickListener(v -> switchPlayer());
    }

    public interface OnSwitchPlayerListener {
        void onSwitchPlayer(int currentPlayer, boolean cmd);
    }

    @Override
    public void pause() {
        super.pause();
        mediaSyncMini.pause();
    }

    @Override
    public void resume() {
        super.resume();
        mediaSyncMini.resume();
    }

}
